/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.distribution.common.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.PhoneUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.PrincipalUtil;
import com.yami.shop.distribution.common.constants.DistributionUserIncomeTypeEnum;
import com.yami.shop.distribution.common.dao.DistributionUserWalletBillMapper;
import com.yami.shop.distribution.common.dao.DistributionUserWalletMapper;
import com.yami.shop.distribution.common.dto.DistributionUserWalletDto;
import com.yami.shop.distribution.common.model.DistributionUserIncome;
import com.yami.shop.distribution.common.model.DistributionUserWallet;
import com.yami.shop.distribution.common.model.DistributionUserWalletBill;
import com.yami.shop.distribution.common.service.DistributionUserIncomeService;
import com.yami.shop.distribution.common.service.DistributionUserWalletService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author lgh on 2019/04/01.
 */
@Service
@RequiredArgsConstructor
public class DistributionUserWalletServiceImpl extends ServiceImpl<DistributionUserWalletMapper, DistributionUserWallet> implements DistributionUserWalletService {

    @Value("${yami.expose.operation.auth:}")
    private Boolean permission;

    @Autowired
    private DistributionUserWalletMapper distributionUserWalletMapper;

    @Autowired
    private DistributionUserWalletBillMapper distributionUserWalletBillMapper;

    @Autowired
    private DistributionUserIncomeService distributionUserIncomeService;


    @Override
    public Long getWalletIdByDistributionUserId(Long distributionUserId) {
        return distributionUserWalletMapper.getWalletIdByDistributionUserId(distributionUserId);
    }

    @Override
    public Page<DistributionUserWallet> getDistributionUserWalletAndDistributionUserVoPage(Page page, String userMobile) {
        Page<DistributionUserWallet> walletPage = distributionUserWalletMapper.getDistributionUserWalletAndDistributionUserVoPage(page, userMobile);
        if (BooleanUtil.isFalse(permission)) {
            for (DistributionUserWallet record : walletPage.getRecords()) {
                record.getDistributionUser().setUserMobile(PhoneUtil.hideBetween(record.getDistributionUser().getUserMobile()).toString());
                if (PrincipalUtil.isMobile(record.getDistributionUser().getNickName())) {
                    record.getDistributionUser().setNickName(PhoneUtil.hideBetween(record.getDistributionUser().getNickName()).toString());
                }
            }
        }
        //计算累计收益
        for (DistributionUserWallet record : walletPage.getRecords()) {
            Double haveWithdrawalSum = distributionUserWalletBillMapper.getHaveWithdrawalSum(record.getWalletId());
            record.setAddupAmount(haveWithdrawalSum+record.getSettledAmount());
        }
//        List<DistributionUserWallet> records = walletPage.getRecords();
//        for (int i = 0; i < records.size(); i++) {
//            Double haveWithdrawalSum = distributionUserWalletBillMapper.getHaveWithdrawalSum(records.get(i).getWalletId());
//            records.get(i).setAddupAmount(haveWithdrawalSum+records.get(i).getSettledAmount());
//        }
//        walletPage.setRecords(records);
        return walletPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDistributionUserWallet(DistributionUserWallet distributionUserWallet, Long modifier) {
        //获取到变动前的钱包
        DistributionUserWallet oldDistributionUserWallet = distributionUserWalletMapper.selectById(distributionUserWallet.getWalletId());

        //变动数额
        Double settledAmount = distributionUserWallet.getChangeAmount();

        // 可提现金额不能小于0
        if (Arith.add(oldDistributionUserWallet.getSettledAmount(), settledAmount) < 0) {
            throw new YamiShopBindException("yami.prod.common.invalid");
        }

        // 可提现金额没有变动，不需要继续执行
        if (settledAmount == 0) {
            return;
        }

        // 待结算金额和失效金额不能更改-如果平台减少用户待结算金额,且订单待结算的金额大于用户的结算金额, 在系统结算订单后用户待结算金额会小于0 (结算时: 订单待结算金额 - 用户待结算金额 = 用户剩余待结算金额)
        distributionUserWallet.setUnsettledAmount(null);
        distributionUserWallet.setInvalidAmount(null);

        double addupAmount = 0;
        // 提现金额增加时,积累收益也要对应增加
        if (settledAmount > 0) {
            addupAmount = settledAmount;
            distributionUserWallet.setAddupAmount(Arith.add(addupAmount, oldDistributionUserWallet.getAddupAmount()));
        }


        // 根据变化的金额,重新计算要钱包的变动金额
        //修改钱包-只变动提现金额和积累收益
        distributionUserWalletMapper.updateSettledAmount(distributionUserWallet.getDistributionUserId(), settledAmount);
        //增加钱包流水记录
        DistributionUserWalletBill distributionUserWalletBill = new DistributionUserWalletBill(distributionUserWallet, "人工修改", "Manual modification", 0D, settledAmount, 0D, addupAmount, 1);
        distributionUserWalletBill.setModifier(modifier);
        // 可提现金额发生变动时，增加或减少用户收益明细
        saveDistributionUserIncome(oldDistributionUserWallet, settledAmount);

        distributionUserWalletBillMapper.insert(distributionUserWalletBill);
    }

    private void saveDistributionUserIncome(DistributionUserWallet oldDistributionUserWallet, Double addupAmount) {
        DistributionUserIncome distributionUserIncome = new DistributionUserIncome();
        distributionUserIncome.setWalletId(oldDistributionUserWallet.getWalletId());
        distributionUserIncome.setIncomeType(DistributionUserIncomeTypeEnum.PLATFORM.getValue());
        distributionUserIncome.setIncomeAmount(addupAmount);
        distributionUserIncome.setDistributionUserId(oldDistributionUserWallet.getDistributionUserId());
        distributionUserIncome.setCreateTime(new Date());
        distributionUserIncome.setUpdateTime(new Date());
        distributionUserIncomeService.save(distributionUserIncome);
    }

    @Override
    public DistributionUserWalletDto getDistributionUserWalletDtoByDistributionUserId(Long distributionUserId) {
        return distributionUserWalletMapper.getDistributionUserWalletDtoByDistributionUserId(distributionUserId);
    }


}
